package com.kot32.dynamicloadviewlibrary.util;


import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

import java.util.Map;
import java.util.Set;

public class PreferenceManager {

    private PreferenceManager() {
    }

    private static Preferences preferences;

    public static Preferences getPreferences() {
        return preferences;
    }


    private static final String DEFAULT_PREFERENCE_KEY = "default";

    public static void init(Context context) {
        DatabaseHelper databaseHelper = new DatabaseHelper(context.getApplicationContext());
        preferences = databaseHelper.getPreferences(DEFAULT_PREFERENCE_KEY);
    }

    /**
     * 判断是否为第一次进入APP
     *
     * @return
     */
    public static boolean isFirstInitAPP() {
        boolean b = preferences.getBoolean("first_init_app", true);
        if (b) {
            addBooleanPreference("first_init_app", false);
        }
        return b;
    }

    /**
     * 判断是否第一次xxx
     */
    public static boolean isFirstXXX(String key) {
        boolean b = preferences.getBoolean(key, true);
        if (b) {
            addBooleanPreference(key, false);
        }
        return b;
    }

    private static void checkIfNull() {
        if (preferences == null) {
            LogUtil.i("警告未初始化偏好设置管理器");
            return;
        }
    }

    public static void addBooleanPreference(String key, boolean b) {
        checkIfNull();
        preferences.putBoolean(key, b);
        preferences.flushSync();
    }


    public static void addFloatPreference(String key, float f) {
        checkIfNull();
        preferences.putFloat(key, f);
        preferences.flushSync();
    }

    public static void addIntPreference(String key, int i) {
        checkIfNull();
        preferences.putInt(key, i);
        preferences.flushSync();
    }

    public static void addLongPreference(String key, long l) {
        checkIfNull();
        preferences.putLong(key, l);
        preferences.flushSync();
    }

    public static void addStringPreference(String key, String s) {
        checkIfNull();
        preferences.putString(key, s);
        preferences.flushSync();
    }

    public static void addStringSetPreference(String key, Set<String> stringSet) {
        checkIfNull();
        preferences.putStringSet(key, stringSet);
        preferences.flushSync();
    }

    public static Object getPreference(String key, Object defaultValue) {
        checkIfNull();
        Object res = preferences.getAll().get(key);
        if (res == null)
            return defaultValue;
        else
            return res;
    }

    public static Map<String, ?> getAllPreference() {
        checkIfNull();
        return preferences.getAll();
    }


}
